package org.wxd.account.jpa.user;

import org.wxd.account.domain.user.User;
import org.wxd.account.domain.user.UserOperations;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import java.util.List;
import java.util.Optional;

/**
 * Created by wangxd on 2015/10/30.
 */
public class JpaUserOperations implements UserOperations {

    @PersistenceContext
    private EntityManager em;

    public Optional<User> ofId(String id) {
        return Optional.ofNullable(em.find(User.class,id));
    }

    public Optional<User> ofEmail(String email) {
        List<User> users = em.createQuery(
                "SELECT o FROM User o WHERE o.email = :email", User.class
        ).setParameter("email",email).getResultList();

        return Optional.ofNullable(users.isEmpty() ? null : users.get(0));
    }


    public void store(User user) {
        em.merge(user);
    }

    public void remove(User user) {
        em.remove(user);
    }


}
